<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php
require_once('php_shared/session_to_db.php');

$error_msg = "";

if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
	if( isset($_POST['username'], $_POST['password']) )
	{
		$db_man = new DbUtils();
		
		if( $db_man->connect() )
		{
			$uname = $db_man->set_var($_POST['username']);
			$pwd = $db_man->set_var($_POST['password']);
			$sql = "SELECT id FROM registered_user WHERE username=$uname AND password=$pwd";
			
			$result = $db_man->query($sql);
			session_start();
			if( !$result )
			{
				$error_msg = "An error occured while communicating with database, please try again later.";
				$_SESSION['user_id'] = "";
			}
			elseif( mysql_num_rows($result) == 0 )
			{
				$error_msg = "Username or password is incorrect, please try again.";
				$_SESSION['user_id'] = "";
			}
			elseif( mysql_num_rows($result) == 1 )
			{
				$row = mysql_fetch_assoc($result);	
				$_SESSION['user_id'] = $row['id'];
				header("Location: messenger.php");
			}
			else
			{
				$error_msg = "Database inconsistency, please try again later.";
				$_SESSION['user_id'] = "";
			}
			
			$db_man->close();
		}
	}else{
		$error_msg = "An error occured while communicating with database. Please try again later.";
	}
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Log In | CSE315 IM</title>
    <link href="css/shared.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/remindpwd.js"></script>
</head>

<body>
	
	<div id="container">
        <b class="border1"></b><b class="border2"></b><b class="border3"></b><b class="border4"></b>
		<div class="bordercontent">
            
            <img src="img/CSE315IM_logo.png" width="317" height="79" alt="CSE315 IM Logo" />
       		<br />
            <h3 class="page_title">Sign In</h3>
            <br />
			<form action="login.php" method="post" name="login_form" onSubmit="JavaScript:return check_login_form();">
              <label>Username:</label><br />
              <input name="username" id="username" type="text" size="45" maxlength="20" /><br />
              <br />
              <label>Password:</label><br />
              <input name="password" id="password" type="password" size="45" maxlength="20" /><br />
              <input name="login_button" type="submit" value="Sign In" class="form_submit"/>
			</form>
            <br /><br />
            <label class="error"><?php print $error_msg; ?></label><br />
            <a href="registration.php">New user?</a><br />
            
  		</div><!-- end #bordercontent -->
	    <b class="border4"></b><b class="border3"></b><b class="border2"></b><b class="border1"></b>
    </div><!-- end #container -->
    
</body>
</html>